﻿using Admin2020.Core.Helper;
using Admin2020.Data.Data;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Admin2020.Service.DependencyRegistrar
{
    public static class ServiceExtension
    {
        /// <summary>
        /// 注册服务的扩展静态方法
        /// </summary>
        /// <param name="services"></param>
        public static void Registar(this IServiceCollection services)
        {
            //services.AddWorkflow(x => x.UseSqlServer(@"Server=.;Database=WorkflowCore;Trusted_Connection=True;", true, true));

            services.AddScoped(typeof(IRepository<>), typeof(EfRepository<>));

            //services.AddTransient<IWebHelper, WebHelper>();
            //services.AddScoped<ILogger, Logger.Logger>();

            //注册需要的服务
            //找出所有 Admin2020.Service 下的类型(会有一些包含了+号等的类型，需要过滤掉)
            var serviceTypes = RuntimeHelper.GetTypesByAssembly("Admin2020.Service")
            .Where(x => (x.FullName.Contains("Admin2020.Service.CommonService") || x.FullName.Contains("MyAdmin.Service.AppService") || x.FullName.Contains("MyAdmin.Service.ShoppingMall")) && !x.FullName.Contains("+"));

            foreach (var type in serviceTypes)
            {
                services.AddTransient(type);
            }
        }

        public static T GetScopedService<T>(this IServiceProvider serviceProvider) where T : class
        {
            var scope = serviceProvider.CreateScope();
            var service = scope.ServiceProvider.GetService(typeof(T)) as T;
            return service;
        }
    }
}
